package com.trkj.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.CcDeductDAO;
import com.trkj.dao.jpa.CcPatientDAO;
import com.trkj.dao.jpa.CcPrepaymentDAO;
import com.trkj.pojos.CcDeduct;
import com.trkj.pojos.CcPatient;
import com.trkj.pojos.CcPrepayment;
import com.trkj.vo.CcDeductVo;

@Service
@Transactional
public class CcDeductService {

	@Autowired
	private CcDeductDAO cdDAO;
	@Autowired
	private CcPrepaymentDAO ccppDAO;
	@Autowired
	private CcPatientDAO ccpDAO;
	public Map<String,Object> queryCcDeduct(int page,int rows,String icid,Date olddate,Date newdate){
		CcPatient cp=ccpDAO.findByOneCcPatient(new BigDecimal(icid));
		CcPrepayment cpp=ccppDAO.findBypatient(new BigDecimal(cp.getPatientid()));
		PageRequest pr = new PageRequest(page - 1, rows);
		List<CcDeduct> list =new ArrayList<>();
		long total=0;
		//如果结束时间小于开始时间
		//System.err.println(newdate.getTime());
		//System.err.println(olddate.getTime());
		
		if(olddate!=null&&newdate!=null){
			if(newdate.getTime()<olddate.getTime()){
				Date d=olddate;
				olddate=newdate;
				newdate=d;
			}
			list=cdDAO.findBydedate(pr, new BigDecimal(cpp.getPpaymentid()),olddate,newdate);
			total=cdDAO.findBydedateCount(new BigDecimal(cpp.getPpaymentid()),olddate,newdate);
			
		}else{
			list=cdDAO.findByOneCcPatient(pr, new BigDecimal(cpp.getPpaymentid()));
			total=cdDAO.findByCount(new BigDecimal(cpp.getPpaymentid()));
		
		}
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", ccDeductToCcDeductVo(list));
		
		return map;
	}
	public List<CcDeductVo> ccDeductToCcDeductVo(List<CcDeduct> list){
		
		List<CcDeductVo> listVo =new ArrayList<CcDeductVo>();
		for(CcDeduct cd :list){
			CcDeductVo cdvo=new CcDeductVo();
			cdvo.setDeductid(cd.getDeductid());
			cdvo.setDedate(cd.getDedate());
			cdvo.setDmoney(cd.getDmoney());
			cdvo.setDpaymentid(cd.getDpaymentid());
			CcPrepayment cpm =ccppDAO.findOne(cdvo.getDpaymentid().longValue());
			CcPatient cp=ccpDAO.findOne(cpm.getPpatientno().longValue());
			cdvo.setIcid(cp.getIcid());
			cdvo.setPatientid(cp.getPatientid());
			cdvo.setPname(cp.getPname());
			listVo.add(cdvo);
		}
		return listVo;
	}
	
}
